package com.house365.core.thirdpart.auth;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.house365.core.R;
import com.house365.core.action.ActionTag;
import com.house365.core.constant.CorePreferences;
import com.house365.core.view.LoadingDialog;
/**
 * @author lzq
 * @date 2013-5-6 
 * @comment Thirdpart Authorize webview page ：Weibo Share or SSO
 */
public abstract class ThirdPartAuthActivity extends Activity implements ThirdPartAuthListener,PageLoadingListener{
	public final static String RESPONSE_TYPE_KEY = "response_type";
	public final static String RESPONSE_TYPE_SERVER_SIDE = "code";
	public final static String RESPONSE_TYPE_CLIENT_SIDE = "token";
	private WebView webView;

	private AuthHandler authHandler;
	protected Activity thisInstance; 
	protected LoadingDialog tloadingDialog ;
//	private AsyncImageLoader mAil;
//	protected BaseApplication mApplication;
	protected AlertDialog.Builder alertDialog;
	private String response_type;
	
	private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			finish();
		}
	};
	
	protected void onCreate(android.os.Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		thisInstance = this;
//		mApplication = (BaseApplication) getApplication();
		registerReceiver(mLoggedOutReceiver, new IntentFilter(
				ActionTag.INTENT_ACTION_LOGGED_OUT));
		response_type = getIntent().getStringExtra(RESPONSE_TYPE_KEY);
		preparedCreate(savedInstanceState);
		initView();
		initData();
	}
	
	protected abstract void preparedCreate(android.os.Bundle savedInstanceState);
	protected abstract void initView();
	
	protected void initData() {
		clearCookies();
		authHandler =initWeiboConfig();
		webView = getWebView();
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebViewClient(new WebViewClient() {

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				if(authHandler.handleAuth(view, url)){
					return;
				}else {
					super.onPageStarted(view, url, favicon);
				}
				ThirdPartAuthActivity.this.onPageStarted();
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				dismissLoadingDialog();
				ThirdPartAuthActivity.this.onPageFinished();
			}
		});

		List<NameValuePair> oList = new ArrayList<NameValuePair>();
		oList.add(new BasicNameValuePair("client_id", authHandler.getAppKeyInfo().getApp_key()));
		oList.add(new BasicNameValuePair("response_type", response_type));
		oList.add(new BasicNameValuePair("redirect_uri", authHandler.getAppKeyInfo().getRedirect_uri()));
		oList.add(new BasicNameValuePair("display", "mobile"));
		if(RESPONSE_TYPE_SERVER_SIDE.equals(response_type)) {
			oList.add(new BasicNameValuePair("state", UUID.randomUUID().toString()));
			oList.add(new BasicNameValuePair("scope", "get_simple_userinfo,get_user_info"));
		}
		String url = URLUtil.genrateGetUrl(Thirdpart.getInstace(this).getAuthUrl(authHandler.getAppKeyInfo().getType()), oList);
		CorePreferences.DEBUG("thirdpart authenrize url : " + url);
		webView.loadUrl(url);
	}
	public void clearCookies() {
        CookieSyncManager cookieSyncMngr =
            CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
    }

	protected void onDestroy() {
		super.onDestroy();
		dismissLoadingDialog();
		tloadingDialog = null;
//		alertDialog = null;
//		if(mAil!= null){
//			mAil.clearCacheImage();
//		}
		clean();
//		mApplication.onAppCancel();
		unregisterReceiver(mLoggedOutReceiver);
	}

	private LoadingDialog getLoadingDialog(){
		if(tloadingDialog == null){
			tloadingDialog= new LoadingDialog(this,
					R.style.dialog, R.string.loading);
			tloadingDialog.setCancelable(isCancelDialog());
			if(isCancelDialog()){
				tloadingDialog.setOnCancelListener(new OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
						onExitDialog();
					}
				});
			}
		
		}
		return tloadingDialog;
	}
	 
	public void showLoadingDialog(){
		if(getLoadingDialog() != null){
			getLoadingDialog().show();
		}
	}
	public void showLoadingDialog(int resid){
		if(getLoadingDialog() != null){
			getLoadingDialog().setMessage(this.getResources().getString(resid));
			getLoadingDialog().show();
		}
	}
	public void dismissLoadingDialog(){
		if(getLoadingDialog() != null){
			getLoadingDialog().dismiss();
		}
	}
	public AlertDialog.Builder getAlertDialog(){
		if(alertDialog == null){
			alertDialog = new AlertDialog.Builder(this);
		}
		return alertDialog;
	}
	
	public void showToast(String str){
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
	}
	public void showToast(int resId){
		Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
	}
	public void onExitDialog(){
		thisInstance.finish();
	}
	public boolean isCancelDialog(){
		return true;
	}
	
	protected  void clean(){
		
	}


	protected abstract WebView getWebView();
	protected abstract AuthHandler initWeiboConfig();
	
}
